package stu.day1_day8;

import java.util.ArrayDeque;

public class LeetCode394 {
    public String decodeString(String s) {
        ArrayDeque<String> stack = new ArrayDeque<>();
        for(int i=0;i<s.length();i++){
            char ch = s.charAt(i);

            if(Character.isDigit(ch)){
                String str ="";
                str = str + ch;
                while (i+1<s.length()&&Character.isDigit(s.charAt(i+1))){
                    i += 1;
                    ch =s.charAt(i);
                    str = str + ch;
                }
                stack.push(str);
            }else if(Character.isAlphabetic(ch)){
                String str ="";
                str = str + ch;
                while (i+1<s.length()&&Character.isAlphabetic(s.charAt(i+1))){
                    i += 1;
                    ch =s.charAt(i);
                    str = str + ch;
                }
                stack.push(str);
            }else if(ch == ']'){
                String str ="";
                while (!stack.isEmpty() && !stack.peek().matches("\\d+")){
                    str = stack.pop() +str;
                }
                int num = Integer.parseInt(stack.pop());
                String newstr= "";
                for (int k=0 ;k<num;k++){
                    newstr = newstr + str;
                }
                stack.push(newstr);
            }
        }

        String fstr = "";
        while (!stack.isEmpty()){
            fstr = stack.pop()+fstr;
        }

        return fstr;


    }
}
